import { spawn } from 'child_process'
import os from 'os'
import { IpcTerminalKeys } from '../../../common/enums/ipc.terminal.enum'
// 存储当前终端进程
// let terminalProcess: any = null

// 注册IPC事件处理
export class TerminalApi {
  static terminalProcess: any = null
  // 1. 启动终端进程
  static start() {
    // 终止已有进程
    if (this.terminalProcess) {
      this.terminalProcess.kill()
    }
    // 根据操作系统获取默认shell
    const getDefaultShell = () => {
      switch (os.platform()) {
        case 'win32':
          return process.env.comspec || 'cmd.exe'
        case 'darwin':
          return '/bin/bash'
        case 'linux':
          return '/bin/bash'
        default:
          return '/bin/sh'
      }
    }
    const shell = getDefaultShell()
    const args = os.platform() === 'win32' ? ['/k'] : ['-i'] // windows下使用cmd.exe，macOS和Linux下使用bash脚本

    // 启动shell进程
    this.terminalProcess = spawn(shell, args, {
      stdio: ['pipe', 'pipe', 'pipe'],
      shell: true,
      env: process.env
    })
    this.listenEvents()

    return {
      shell,
      pid: this.terminalProcess.pid
    }
  }
  // 2. 向终端发送命令
  static send(_, command: string) {
    if (!this.terminalProcess) {
      return false
    }
    try {
      this.terminalProcess.stdin.write(command + '\n')
      return true
    } catch (error) {
      console.error('Failed to send command:', error)
      return false
    }
  }
  // 3. 终止终端
  static kill() {
    if (this.terminalProcess) {
      this.terminalProcess.kill()
      this.terminalProcess = null
      return true
    }
    return false
  }
  // 4. 清屏
  static clear() {
    // 向渲染进程发送清屏信号
    global.mainWindow?.webContents.send(IpcTerminalKeys.TERMINAL_CLEAR)
    return true
  }
  // 5. 监听事件
  static listenEvents() {
    // 监听标准输出
    this.terminalProcess.stdout.on('data', (data: Buffer) => {
      // 发送输出到渲染进程
      global.mainWindow?.webContents.send(IpcTerminalKeys.TERMINAL_OUTPUT, data.toString())
    })

    // 监听错误输出
    this.terminalProcess.stderr.on('data', (data: Buffer) => {
      global.mainWindow?.webContents.send(IpcTerminalKeys.TERMINAL_OUTPUT, data.toString())
    })

    // 监听进程退出
    this.terminalProcess.on('exit', (code: number) => {
      global.mainWindow?.webContents.send(IpcTerminalKeys.TERMINAL_EXIT, code)
      this.terminalProcess = null
    })

    // 监听进程错误
    this.terminalProcess.on('error', (err: Error) => {
      global.mainWindow?.webContents.send(IpcTerminalKeys.TERMINAL_ERROR, err.message)
      this.terminalProcess = null
    })
  }
}
